#include "StdAfx.h"
#include "Triangle.h"

CTriangle::CTriangle(const CPoint3D& p1, const CPoint3D& p2, const CPoint3D& p3)
{
	SetPoints(p1,p2,p3);
}

CTriangle::~CTriangle(void)
{

}
void CTriangle::SetPoints(const CPoint3D& _p1, const CPoint3D& _p2, const CPoint3D& _p3)
{
	p1 = _p1;
	p2 = _p2;
	p3 = _p3;
	Point = p1;
	Normal = (p2 - p1).Cross(p3 - p2);
	Normal.Normalize();
}
float CTriangle::Intersect(CRay& ray, CPoint3D& intersection, CPoint3D& normal)
{
	float dist = CPlane::Intersect(ray,intersection,normal);
	if (dist < 0.f) return -1.f;
	CPoint3D a = p2 - p1;
	CPoint3D b = p3 - p2;
	CPoint3D c = p1 - p3;
	
	CPoint3D crossA = a.Cross(intersection - p1);
	if (crossA.Dot(Normal) < 0.f) return -1.f;
	CPoint3D crossB = b.Cross(intersection - p2);
	if (crossB.Dot(Normal) < 0.f) return -1.f;
	CPoint3D crossC = c.Cross(intersection - p3);
	if (crossC.Dot(Normal) < 0.f) return -1.f;

	return dist;
}